from sqlalchemy import select, text

from src.db.crud import insert_topic_scoliosis_message
from src.db.models import Files
from src.db.session import DatabaseSession
from src.kafka.message_structures.radiology_ct.scoliosis import TopicScoliosisMessage
from src.utils import generate_uuid_name


class Anonymizer:
    def __init__(self, db_client: DatabaseSession):
        self.db_client = db_client

    async def anonymize(self, topic_scoliosis_message: TopicScoliosisMessage) -> None:
        new_name = generate_uuid_name()
        while await self._check_name_in_db(new_name):
            new_name = generate_uuid_name()

        await self._insert_into_db(topic_scoliosis_message, new_name)

    async def _check_name_in_db(self, new_name: str):
        async_session = await self.db_client.get_session()
        result = await async_session.execute(
            text("SELECT 1 FROM files WHERE name = :name"), {"name": new_name}
        )
        return result.scalar() is not None

    async def _insert_into_db(self, topic_scoliosis_message: TopicScoliosisMessage, new_name: str):
        await insert_topic_scoliosis_message(topic_scoliosis_message, self.db_client)
        file = await self.db_client.execute(
            select(Files).where(Files.id == str(topic_scoliosis_message.id_))
        )
        file = file.scalars().first()
        file.name = new_name
        await self.db_client.commit()
